<!-- 按钮控件组 -->
<div class="row">
    <div><button type="button" id="role_add" class="btn btn-success" data-toggle="modal" data-target="#myModal">添加</button></div>
    <div><input id="role_name" type="text" class="form-control" placeholder="请输入用户名"></div>
    <div><select name="" id="role_select" class="form-control">
      <option value="">请选择角色</option>
    </select></div>
    <div><button id="role_search" class="btn btn-primary">搜索</button></div>
</div>
<!-- 表格 -->
<table class="table table-hover" id="role_table">
    <thead>
        <td>序号</td>
        <td>用户名</td>
        <td>姓名</td>
        <td>角色</td>
        <td>性别</td>
        <td>状态</td>
        <td>手机号</td>
        <td>操作</td>
    </thead>
    <tbody></tbody>
</table>
<!-- 分页代码 -->
<nav aria-label="Page navigation">
    <ul class="pagination">
        <li class="currentnum">
            <a href="#" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>

        <li>
            <a href="#" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    </ul>
</nav>
<!-- 新增修改的模态框Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <div class="dialog-center">
                    <div>
                        用户名:
                        <input class="form-control" type="text" name="username">
                    </div>
                    <div>
                        密码:
                        <input class="form-control" type="text" name="password">
                    </div>
                    <div>
                        姓名:
                        <input class="form-control" type="text" name="realname">
                    </div>
                    <div>
                        状态:
                        <input class="form-control" type="text" name="status">
                    </div>
                    <div>
                        电话:
                        <input class="form-control" type="text" name="telephone">
                    </div>
                    <div class="radio-inline">
                        性别:
                    </div>
                    <div class="radio-inline">
                        <input type="radio" name="gender" value="male" checked="true" id="male"><label for="male">男</label>
                    </div>
                    <div class="radio-inline">
                        <input type="radio" name="gender" value="female" id="female"><label for="female">女</label>
                    </div>
                    <div>出生日期:
                        <input type="date" id="birth"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel">取消</button>
                <button type="button" class="btn btn-primary" id="role_submit">提交</button>
            </div>
        </div>
    </div>
</div>
<!-- 设置按钮的模态框 -->
<div class="modal fade" id="setModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">设置用户角色</h4>
            </div>
            <div class="modal-body">
                <b>用户名:&nbsp;</b><input class="form-control" id="disabledInput" type="text" placeholder="" disabled>
                <br>
                <div class="radio-inline">
                    <b>角色:</b>
                </div>
                <div class="radio-inline">
                    <input type="radio" name="roles" value="2">管理员
                </div>
                <div class="radio-inline">
                    <input type="radio" name="roles" value="1">教师
                </div>
                <div class="radio-inline">
                    <input type="radio" name="roles" value="6">学生
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="role_save">保存</button>
            </div>
        </div>
    </div>
</div>
<!-- JS代码 -->
<script>
    var user; //用来接收用户信息
    var page = 1; //设置起始页
    var pageSize = 10; //设置每页信息数量
    //封装将数据插入表格方法
    function roleget(res) {
        // console.log(res);
        //清空tbody
        $('#role_table tbody').empty();
        $('#role_table #role_ckbox').empty();
        res.data.list.forEach(function(item, index) {
            var newTr = $(`<tr>
                          <td>${index + 1}</td>
                          <td>${item.username}</td>
                          <td>${item.realname}</td>
                          <td>${item.roles.map(function (itemroles) {return itemroles.name}).join()}</td>
                          <td>${item.gender === 'male' ? '男' : '女'}</td>
                          <td>${item.status}</td>
                          <td>${item.telephone}</td>
                          <td>
                          <button  data-item='${JSON.stringify(item)}' class="btn btn-default" id="role_set" data-toggle="modal" data-target="#setModal">设置</button>
                          <button data-id="${item.id}" class="btn btn-danger" id="role_delete">移除</button>
                          <button data-id="${item.id}" class="btn btn-info" id="role_more">详情</button>
                          <button data-item='${JSON.stringify(item)}' class="btn btn-default" id="role_update" data-toggle="modal" data-target="#myModal">修改</button>
                          </td>
                      </tr>`);

            $('#role_table tbody').append(newTr)
        })
    }
    //封装分页查询方法
    function roleMassageget() {
        $.get(baseURL + '/baseUser/pageQuery', {
            page,
            pageSize
        }, function(res) {
            roleget(res)
        })
    }
    roleMassageget();

    //查询角色下拉菜单
    $.get(baseURL + '/role/findAll', function(res) {
        // console.log(res);
        //清空下拉列表
        $('#role_select').empty();
        $('#role_select').append(`<option value="">请选择角色</option>`)
        res.data.forEach(function(item) {
            var newOpt = $(`
              <option>${item.name}</option>
              `)
            $('#role_select').append(newOpt)
        })
    })

    //插入分页
    $.get(baseURL + '/baseUser/findAll', function(res) {
        // console.log(res);
        // alert(res.data.length)
        //清空分页
        if ($(".clicknum.length") > 0) {
            $(".clicknum").remove();
        }
        var num = Math.ceil(res.data.length / pageSize);
        for (var i = num; i > 0; i--) {
            $('.currentnum').after(
                '<li class="clicknum"><a href="#">' + i + '</a></li>')
        }
    })

    //搜索功能
    $("#role_search").click(function() {
        $('#role_table tbody').empty();
        var username = $("#role_name").val();
        var rolename = $("#role_select").val();
        console.log(username, rolename);
        $.get(baseURL + '/baseUser/pageQuery', {
            page,
            pageSize,
            username,
            rolename
        }, function(res) {
            roleget(res)
        });
    })

    //点击页码事件
    $('.pagination').click(function() {
        //清空分页
        if ($(".clicknum.length") > 0) {
            $(".clicknum").remove();
        }
        // alert($(event.target).text())
        page = $(event.target).text();
        roleMassageget();
    })

    //添加功能
    $("#role_add", ).click(function() {
        //清空user,设置模态框头部
        user = null;
        $('.modal-title').html('新增用户信息');
        //清空表单数据
        $('input[name=username]').val('');
        $('input[name=password]').val('');
        $('input[name=realname]').val('');
        $('input[name=telephone]').val('');
        $('input[name=status]').val('');
        $('input[name=gender]').prop('checked', false);
        $('input[id=birth]').val('');
    });

    //修改功能事件代理 id="role_update"
    $('#role_table tbody').on('click', '#role_update', function() {
        user = $(this).attr('data-item');
        user = JSON.parse(user);
        console.log(user);
        $('input[name=username]').val(user.username);
        $('input[name=password]').val(user.password);
        $('input[name=realname]').val(user.realname);
        $('input[name=telephone]').val(user.telephone);
        $('input[name=status]').val(user.status);
        $('input[name=gender][value=' + user.gender + ']').prop('checked', true);
        $('input[id=birth]').val('');
        if (user.birth != null) {
            $(function() {
                //创建一个当前日期对象
                var date = new Date(user.birth);
                //格式化日，如果小于9，前面补0
                var day = ("0" + date.getDate()).slice(-2);
                //格式化月，如果小于9，前面补0
                var month = ("0" + (date.getMonth() + 1)).slice(-2);
                //拼装完整日期格式
                var birth = date.getFullYear() + "-" + (month) + "-" + (day);
                //完成赋值
                $("input[id=birth]").val(birth);
            })
        }
        //设置模态框标题
        $('.modal-title').html('修改用户信息')
    });

    //新增修改提交按钮  新增:保存数据  修改:更新数据   传id代表修改,不传id代表新增
    $("#role_submit").click(function() { //给后加的节点绑定事件
        //获取用户输入的信息
        var username = $('input[name=username]').val();
        var password = $('input[name=password]').val();
        var realname = $('input[name=realname]').val();
        var telephone = $('input[name=telephone]').val();
        var status = $('input[name=status]').val();
        var gender = $('input[name=gender]:checked').val();
        var birth = (new Date($('input[id=birth]').val())).valueOf();
        console.log(username, password, realname, telephone, gender, birth);
        //访问后台接口,保存到数据库,保存成功之后刷新数据
        $.post(baseURL + '/baseUser/saveOrUpdate', {
            id: user ? user.id : '',
            username: username,
            password: password,
            realname: realname,
            telephone: telephone,
            status: status,
            gender: gender,
            birth: birth
        }, function(res) {
            //提示保存成功
            if (res.status == 200) {
                alert('保存成功');
                roleMassageget();
            }
        });
        $("#myModal").modal("hide");
        $('.modal-backdrop').remove(); //去掉遮罩层
    })

    //设置点击功能,事件代理
    $('#role_table tbody').on('click', '#role_set', function() {
        user = $(this).attr('data-item');
        // alert(user)
        user = JSON.parse(user);
        $('input[id=disabledInput]').val(user.username);
        console.log(user.roles);
        if (user.roles) {
            $('input[name=roles][value=' + user.roles.map(function(itemroles) {
                return itemroles.id
            }).join() + ']').prop('checked', true);
        }

    })

    //角色设置提交
    $("#role_save").click(function() {
        var roles = $('input[name=roles]:checked').val();
        $.post(baseURL + '/baseUser/setRoles', {
            id: user.id,
            roles: roles
        }, function(res) {
            // alert(res.message)
            // console.log(res);
            roleMassageget();
        })
        $("#setModal").modal("hide")
        $('.modal-backdrop').remove(); //去掉遮罩层
    })

    //详情按钮 id="role_more"
    $('#role_table tbody').on('click', '#role_more', function() {
        // 获取当前点击用户id
        var userid = $(this).attr('data-id');
        // 将id存储并加载详情页面
        sessionStorage.setItem("userid", userid)
        $(".content-main").load('./pages/userMessage.html');
    })

    //移除功能,事件代理 id="role_delete"
    $('#role_table tbody').on('click', '#role_delete', function() {
        // console.log(this);
        //获取data-id值 attr
        //attr('name','test') prop()
        var id = $(this).attr('data-id');
        // console.log(id);
        if (confirm('确认删除?')) {
            $.get(baseURL + '/baseUser/deleteById', {
                id: id
            }, function(res) {
                console.log(res);
                roleMassageget();
            });
        }
    });
</script>

<!-- css样式 -->
<style>
    #role_name {
        width: 170px;
    }
    
    label,
    #date {
        cursor: pointer;
    }
</style>